package com.nanbei.sort;

import java.util.Arrays;

/**
 * @ClassDescription: 计算排序
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/6/28 10:47
 */
public class CountingSort {

    public static void main(String[] args) {
        int[] ints = countSort(new int[]{1, 5, 7, 4, 2, 6, 7, 7, 4, 3, 9, 7,-1,-2,-3});
        System.out.println(Arrays.toString(ints));
    }

    /**
     * 限制: 元素的值不能过大，不能有负数（如果有负数需要进行映射）
     * @param nums 计数排序数组
     * @return 排序后的数组
     */
    public static int[] countSort(int[] nums){
        if (nums.length ==0){
            return nums;
        }
        int max = nums[0];
        int min = nums[0];
        for (int num : nums) {
            if (max <num){
                max = num;
            }
            if (min > num){
                min = num;
            }
        }
        int[] ints = new int[max- min +1];
        for (int num : nums) {
            ints[num-min]++;
        }

        int index = 0;
        for (int i = 0; i < ints.length; i++) {
            while (ints[i] >0){
                nums[index++] = i+min;
                ints[i]--;
            }
        }
        return nums;
    }
}
